package com.example.mall_system.service.Impl;

import com.example.mall_system.common.Result;
import com.example.mall_system.entity.*;
import com.example.mall_system.mapper.*;
// 移除未使用的导入语句
import com.example.mall_system.service.OrdersService;
import com.example.mall_system.service.ProductService;
// 移除未使用的导入语句
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private CartItemMapper cartItemMapper;

    @Autowired
    private ProductService productService;

    @Autowired
    private AddressMapper addressMapper;

    @Override
    @Transactional
    public Result<Order> createOrder(Long userId, Long addressId, List<Long> cartItemIds) {
        // 验证用户ID
        if (userId == null) {
            return Result.error(400, "用户ID不能为空");
        }
        
        // 验证地址
        Address address = addressMapper.selectByIdAndUserId(addressId, userId);
        if (address == null) {
            return Result.error(404, "收货地址不存在");
        }

        // 获取购物车项
        List<CartItem> cartItems = new ArrayList<>();
        for (Long id : cartItemIds) {
            CartItem item = cartItemMapper.findById(id.intValue());
            if (item == null || !item.getUserId().equals(userId)) {
                return Result.error(404, "购物车项不存在或不属于当前用户");
            }
            cartItems.add(item);
        }

        if (cartItems.isEmpty()) {
            return Result.error(400, "购物车为空");
        }

        // 检查库存并计算总价
        BigDecimal totalPrice = BigDecimal.ZERO;
        for (CartItem item : cartItems) {
            Result<?> stockResult = productService.checkAndUpdateStock(item.getProductId(), item.getQuantity());
            if (stockResult.getCode() != 200) {
                throw new RuntimeException(stockResult.getMessage());
            }

            Product product = (Product) productService.getProductById(item.getProductId()).getData();
            if (product == null) {
                return Result.error(404, "商品不存在: " + item.getProductId());
            }
            totalPrice = totalPrice.add(BigDecimal.valueOf(product.getPrice()).multiply(BigDecimal.valueOf(item.getQuantity())));
        }

        // 创建订单
        Order order = new Order();
        order.setOrderNumber(generateOrderNumber());
        order.setUserId(userId);
        order.setTotalPrice(totalPrice);
        order.setStatus(0); // 待支付
        order.setAddressId(addressId);
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        
        // 验证订单对象
        if (order.getUserId() == null) {
            return Result.error(500, "订单创建失败：用户ID设置异常");
        }
        
        orderMapper.insert(order);

        // 创建订单项
        List<OrderItem> orderItems = new ArrayList<>();
        for (CartItem item : cartItems) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setProductId(item.getProductId());
            orderItem.setQuantity(item.getQuantity());
            Product product = (Product) productService.getProductById(item.getProductId()).getData();
            orderItem.setPrice(BigDecimal.valueOf(product.getPrice()));
            orderItem.setCreateTime(LocalDateTime.now());
            orderItems.add(orderItem);

            // 删除购物车项
            cartItemMapper.deleteById(item.getId());
        }
        orderItemMapper.insertBatch(orderItems);

        return Result.success(order);
    }

    @Override
    @Transactional
    public Result<String> payOrder(Long orderId, Integer paymentMethod) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return Result.error(404, "订单不存在");
        }
        if (order.getStatus() != 0) {
            return Result.error(400, "订单状态错误，只能支付待支付订单");
        }

        // 模拟支付处理
        order.setStatus(1); // 已支付
        order.setPaymentMethod(paymentMethod);
        order.setPaymentTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        order.setUpdateTime(new Date());
        orderMapper.updateStatus(order);

        return Result.success("支付成功");
    }

    @Override
    @Transactional
    public Result<String> cancelOrder(Long orderId, Long userId, Integer role, String cancelReason) {
        // 参数验证
        if (orderId == null) {
            return Result.error(400, "订单ID不能为空");
        }
        if (userId == null) {
            return Result.error(400, "用户ID不能为空");
        }
        if (cancelReason == null || cancelReason.trim().isEmpty()) {
            return Result.error(400, "取消原因不能为空");
        }
        
        // 获取订单信息
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return Result.error(404, "订单不存在");
        }
        
        // 权限判断：买家只能操作自己的订单，卖家/管理员可操作所有订单
        if (role != null && role == 0 && !order.getUserId().equals(userId)) {
            return Result.error(403, "无权操作此订单");
        }
        
        // 检查订单状态
        if (order.getStatus() == 4) {
            return Result.error(400, "订单已经是取消状态");
        }
        if (order.getStatus() == 3) {
            return Result.error(400, "已完成的订单不能取消");
        }
        if (order.getStatus() == 2) {
            return Result.error(400, "已发货的订单不能取消，请联系客服");
        }
        
        // 检查取消时间限制（待支付订单创建后24小时内可取消）
        if (order.getStatus() == 0) {
            long createTime = order.getCreateTime().getTime();
            long currentTime = System.currentTimeMillis();
            long timeLimit = 24 * 60 * 60 * 1000; // 24小时
            
            if (currentTime - createTime > timeLimit) {
                return Result.error(400, "订单创建超过24小时，无法取消，请联系客服");
            }
        }
        
        // 检查取消时间限制（已支付订单支付后1小时内可取消）
        if (order.getStatus() == 1) {
            if (order.getPaymentTime() != null) {
                try {
                    java.time.LocalDateTime paymentTime = java.time.LocalDateTime.parse(
                        order.getPaymentTime(), 
                        java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                    );
                    java.time.LocalDateTime currentTime = java.time.LocalDateTime.now();
                    java.time.Duration duration = java.time.Duration.between(paymentTime, currentTime);
                    
                    if (duration.toHours() > 1) {
                        return Result.error(400, "支付超过1小时，无法取消，请联系客服");
                    }
                } catch (Exception e) {
                    // 如果时间解析失败，记录日志但继续执行
                    System.err.println("解析支付时间失败: " + e.getMessage());
                }
            }
        }
        
        try {
            // 恢复商品库存
            List<OrderItem> orderItems = orderItemMapper.selectByOrderId(orderId);
            for (OrderItem orderItem : orderItems) {
                Result<?> productResult = productService.getProductById(orderItem.getProductId());
                if (productResult.getCode() == 200 && productResult.getData() != null) {
                    Product product = (Product) productResult.getData();
                    product.setStock(product.getStock() + orderItem.getQuantity());
                    // 修复：传递正确的参数，使用管理员权限来更新商品库存
                    Result<Boolean> updateResult = productService.updateProduct(product, 1L, 2);
                    if (updateResult.getCode() != 200) {
                        System.err.println("恢复商品库存失败: " + updateResult.getMessage());
                        // 继续处理其他商品，不中断整个流程
                    }
                } else {
                    System.err.println("获取商品信息失败: " + productResult.getMessage());
                }
            }
            
            // 更新订单状态
            order.setStatus(4); // 已取消
            order.setCancellationTime(java.time.LocalDateTime.now().format(
                java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
            ));
            order.setCancelReason(cancelReason.trim());
            order.setUpdateTime(new Date());
            
            int updateResult = orderMapper.updateStatus(order);
            if (updateResult > 0) {
                // 记录取消日志
                System.out.println(String.format(
                    "订单取消成功 - 订单号: %s, 用户ID: %d, 角色: %d, 取消原因: %s, 时间: %s",
                    order.getOrderNumber(), userId, role, cancelReason, order.getCancellationTime()
                ));
                
                return Result.success("订单已成功取消");
            } else {
                return Result.error(500, "订单状态更新失败");
            }
            
        } catch (Exception e) {
            System.err.println("取消订单异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error(500, "取消订单失败: " + e.getMessage());
        }
    }

    @Override
    public Result<Map<String, Object>> getOrderById(Long id, Long userId, Integer role) {
        Order order = orderMapper.selectById(id);
        if (order == null) {
            return Result.error(404, "订单不存在");
        }
        if (order.getUserId() == null) {
            return Result.error(500, "订单数据异常：用户ID为空");
        }
        // 权限判断：买家只能操作自己的订单
        if (role != null && role == 0 && !order.getUserId().equals(userId)) {
            return Result.error(403, "无权查看此订单");
        }
        List<OrderItem> orderItems = orderItemMapper.selectByOrderId(id);
        List<Map<String, Object>> itemsWithProductInfo = new ArrayList<>();
        for (OrderItem item : orderItems) {
            Map<String, Object> itemInfo = new HashMap<>();
            itemInfo.put("id", item.getId());
            itemInfo.put("quantity", item.getQuantity());
            itemInfo.put("price", item.getPrice());
            Product product = (Product) productService.getProductById(item.getProductId()).getData();
            if (product != null) {
                itemInfo.put("productId", product.getId());
                itemInfo.put("productName", product.getName());
                itemInfo.put("productImage", product.getImage());
            }
            itemsWithProductInfo.add(itemInfo);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("order", order);
        result.put("items", itemsWithProductInfo);
        Address address = addressMapper.selectByIdAndUserId(order.getAddressId(), userId);
        result.put("address", address);
        return Result.success(result);
    }

    @Override
    public Result<List<Map<String, Object>>> getUserOrders(Long userId) {
        List<Order> orders = orderMapper.selectByUserId(userId);
        
        List<Map<String, Object>> ordersWithDetails = new ArrayList<>();
        
        for (Order order : orders) {
            Map<String, Object> orderInfo = new HashMap<>();
            
            // 订单基本信息
            orderInfo.put("id", order.getId());
            orderInfo.put("orderNumber", order.getOrderNumber());
            orderInfo.put("totalPrice", order.getTotalPrice());
            orderInfo.put("status", order.getStatus());
            orderInfo.put("createTime", order.getCreateTime());
            orderInfo.put("paymentTime", order.getPaymentTime());
            orderInfo.put("shippingTime", order.getShippingTime());
            orderInfo.put("completionTime", order.getCompletionTime());
            orderInfo.put("cancellationTime", order.getCancellationTime());
            
            // 获取订单项和商品信息
            List<OrderItem> orderItems = orderItemMapper.selectByOrderId(order.getId());
            List<Map<String, Object>> itemsWithProductInfo = new ArrayList<>();
            
            for (OrderItem item : orderItems) {
                Map<String, Object> itemInfo = new HashMap<>();
                itemInfo.put("id", item.getId());
                itemInfo.put("quantity", item.getQuantity());
                itemInfo.put("price", item.getPrice());
                
                Product product = (Product) productService.getProductById(item.getProductId()).getData();
                if (product != null) {
                    itemInfo.put("productId", product.getId());
                    itemInfo.put("productName", product.getName());
                    itemInfo.put("productImage", product.getImage());
                }
                
                itemsWithProductInfo.add(itemInfo);
            }
            
            orderInfo.put("items", itemsWithProductInfo);
            
            // 获取地址信息
            Address address = addressMapper.selectByIdAndUserId(order.getAddressId(), userId);
            if (address != null) {
                orderInfo.put("address", address);
            }
            
            ordersWithDetails.add(orderInfo);
        }
        
        return Result.success(ordersWithDetails);
    }

    @Override
    @Transactional
    public Result<String> shipOrder(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return Result.error(404, "订单不存在");
        }
        if (order.getStatus() != 1) {
            return Result.error(400, "只能发货已支付的订单");
        }

        order.setStatus(2); // 已发货
        order.setShippingTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        order.setUpdateTime(new Date());
        orderMapper.updateStatus(order);

        return Result.success("订单已发货");
    }

    @Override
    @Transactional
    public Result<String> completeOrder(Long orderId, Long userId, Integer role) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return Result.error(404, "订单不存在");
        }
        if (order.getUserId() == null) {
            return Result.error(500, "订单数据异常：用户ID为空");
        }
        // 权限判断：买家只能操作自己的订单
        if (role != null && role == 0 && !order.getUserId().equals(userId)) {
            return Result.error(403, "无权操作此订单");
        }
        if (order.getStatus() != 2) {
            return Result.error(400, "只能完成已发货的订单");
        }
        order.setStatus(3); // 已完成
        order.setCompletionTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        order.setUpdateTime(new Date());
        orderMapper.updateStatus(order);
        return Result.success("订单已完成");
    }

    @Override
    public Result<List<Order>> getOrdersByStatus(Long userId, Integer status) {
        List<Order> orders = orderMapper.selectByUserIdAndStatus(userId, status);
        return Result.success(orders);
    }

    @Override
    @Transactional
    public Result<String> updateOrderAddress(Long orderId, Long addressId, Long userId, Integer role) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return Result.error(404, "订单不存在");
        }
        if (order.getUserId() == null) {
            return Result.error(500, "订单数据异常：用户ID为空");
        }
        // 权限判断：买家只能操作自己的订单
        if (role != null && role == 0 && !order.getUserId().equals(userId)) {
            return Result.error(403, "无权操作此订单");
        }
        if (order.getStatus() != 0) {
            return Result.error(400, "只能修改待支付订单的地址");
        }
        Address address = addressMapper.selectByIdAndUserId(addressId, userId);
        if (address == null) {
            return Result.error(404, "收货地址不存在");
        }
        order.setAddressId(addressId);
        order.setUpdateTime(new Date());
        int result = orderMapper.updateAddress(orderId, addressId);
        if (result > 0) {
            return Result.success("订单地址更新成功");
        } else {
            return Result.error(500, "订单地址更新失败");
        }
    }

    private String generateOrderNumber() {
        // 生成订单号：年月日时分秒+4位随机数
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String random = String.format("%04d", new Random().nextInt(10000));
        return "ORD" + timestamp + random;
    }
}